/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.chlitina.store.modules.employee.web;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.chlitina.store.common.config.Global;
import com.chlitina.store.common.mapper.JsonMapper;
import com.chlitina.store.common.persistence.Page;
import com.chlitina.store.common.utils.DateUtils;
import com.chlitina.store.common.utils.Encodes;
import com.chlitina.store.common.web.BaseController;
import com.chlitina.store.modules.cash.entity.StoreConsume;
import com.chlitina.store.modules.cash.service.StoreConsumeBuyProductService;
import com.chlitina.store.modules.cash.service.StoreConsumeDoCareService;
import com.chlitina.store.modules.cash.service.StoreConsumeNewCardService;
import com.chlitina.store.modules.cash.service.StoreConsumeRechargeCardService;
import com.chlitina.store.modules.employee.entity.Employee;
import com.chlitina.store.modules.employee.entity.StoreEmployeeAccounting;
import com.chlitina.store.modules.employee.entity.StoreEmployeeAccountingDetail;
import com.chlitina.store.modules.employee.model.EmployeeAccounting;
import com.chlitina.store.modules.employee.model.EmployeePerformance;
import com.chlitina.store.modules.employee.service.EmployeeService;
import com.chlitina.store.modules.employee.service.StoreEmployeeAccountingService;
import com.chlitina.store.modules.expert.entity.Care;
import com.chlitina.store.modules.sys.utils.StoreUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 员工结算单Controller
 * @author liujiang
 * @version 2013-11-21
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH+"/employee/storeEmployeeAccounting")
public class StoreEmployeeAccountingController extends BaseController {

	@Autowired
	private StoreEmployeeAccountingService storeEmployeeAccountingService;
	@Autowired
	private EmployeeService employeeService;
	@Autowired
	private StoreConsumeBuyProductService storeConsumeBuyProductService;
	@Autowired
	private StoreConsumeDoCareService storeConsumeDoCareService;
	@Autowired
	private StoreConsumeRechargeCardService storeConsumeRechargeCardService;
	@Autowired
	private StoreConsumeNewCardService storeConsumeNewCardService;
	
	@ModelAttribute
	public StoreEmployeeAccounting get(@RequestParam(required=false) Long id) {
		if (id != null){
			return storeEmployeeAccountingService.get(id);
		}else{
			return new StoreEmployeeAccounting();
		}
	}
	
	@RequestMapping(value = {"list", ""})
	public String list(StoreEmployeeAccounting storeEmployeeAccounting, HttpServletRequest request, HttpServletResponse response, Model model) {
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		Page<StoreEmployeeAccounting> page = new Page<StoreEmployeeAccounting>(request, response);
		if(!StringUtils.isEmpty(startDate) || !StringUtils.isEmpty(endDate)){
			page = storeEmployeeAccountingService.find(page, startDate, endDate); 
		}
        model.addAttribute("page", page);
        model.addAttribute("startDate", startDate);
        model.addAttribute("endDate", endDate);
		return "modules/employee/storeEmployeeAccountingList";
	}
	
	public Map<Long, String> getEmployeeMap(String employeeIds) {
		Map<Long, String> employeeMap = Maps.newHashMap();
		String[] ids = employeeIds.split(",");
		for (String id : ids) {
			Employee employee = employeeService.get(Long.parseLong(id));
			employeeMap.put(employee.getId(), employee.getName());
		}
		return employeeMap;
	}
	
	public static float getEmployeeSalary(float salary, Date start, Date end) {
		long off = end.getTime() - start.getTime();
		int days = (int) (off/(24*3600*1000) + 1);
		System.out.println(days);
		BigDecimal money = new BigDecimal(salary*days/30).setScale(2, BigDecimal.ROUND_HALF_UP);
		return money.floatValue();
	}
	
	@ResponseBody
	@RequestMapping(value = "account")
	public String account(StoreEmployeeAccounting storeEmployeeAccounting, HttpServletRequest request, HttpServletResponse response, Model model) {
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		String employeeIds = request.getParameter("employeeIds");
		float allMoney = 0;
		List<EmployeeAccounting> list = Lists.newArrayList();
		if(!StringUtils.isEmpty(startDate) || !StringUtils.isEmpty(endDate)){
			try {
				Date start = null;
				Date end = null;
				if (!StringUtils.isEmpty(startDate)) {
					start = DateUtils.getBeginOfDay(DateUtils.parseDate(startDate));
				}
				if (!StringUtils.isEmpty(endDate)) {
					end = DateUtils.getEndOfDay(DateUtils.parseDate(endDate));
				}
				if (!StringUtils.isEmpty(employeeIds)) {
					String[] ids = employeeIds.split(",");
					for (String id : ids) {
						Employee employee = employeeService.get(Long.parseLong(id));
						if(employee != null) {
							float baseSalary = getEmployeeSalary(employee.getSalary(), start, end);
							float newCardBonus = storeConsumeNewCardService.getByEmployeeBonus(employee, start, end);
							float rechargeCardBonus = storeConsumeRechargeCardService.getByEmployeeBonus(employee, start, end);
							float careCardBonus = storeConsumeDoCareService.getByEmployeeBonus(employee, start, end);
							float productCardBonus = storeConsumeBuyProductService.getByEmployeeBonus(employee, start, end);
							EmployeeAccounting detail = new EmployeeAccounting();
							detail.setBase_salary(baseSalary);
							detail.setTitle(employee.getStoreRole().getName());
							detail.setEmployeeId(employee.getId());
							detail.setEmployeeName(employee.getName());
							detail.setDo_care_bonus(careCardBonus);
							detail.setNew_card_bonus(newCardBonus);
							detail.setProduct_sale_bonus(productCardBonus);
							detail.setRecharge_card_bonus(rechargeCardBonus);
							detail.setFloat_salary(0);
							detail.setRemark("");
							float total = baseSalary + newCardBonus + rechargeCardBonus + careCardBonus + productCardBonus;
							detail.setTotal(total);
							allMoney += total;
							list.add(detail);
						}
					}
				}
			} catch (Exception e) {
			}
		}
		return JsonMapper.getInstance().toJson(list);
	}
	
	@RequestMapping(value = "performance")
	public String performance(HttpServletRequest request, HttpServletResponse response, Model model) {
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		float allMoney = 0;
		List<EmployeePerformance> list = Lists.newArrayList();
		if(!StringUtils.isEmpty(startDate) || !StringUtils.isEmpty(endDate)){
			try {
				Date start = null;
				Date end = null;
				if (!StringUtils.isEmpty(startDate)) {
					start = DateUtils.getBeginOfDay(DateUtils.parseDate(startDate));
				}
				if (!StringUtils.isEmpty(endDate)) {
					end = DateUtils.getEndOfDay(DateUtils.parseDate(endDate));
				}
				List<Employee> employeeList = employeeService.findByStore(StoreUtils.getStore(), Employee.STATUS_WORKING);
				for (Employee employee : employeeList) {
					float newCardCost = storeConsumeNewCardService.getByEmployeeCost(employee, start, end);
					float rechargeCardCost = storeConsumeRechargeCardService.getByEmployeeCost(employee, start, end);
					Map<Integer, Float> map = storeConsumeDoCareService.getByEmployeeCost(employee, start, end);
					float productCardCost = storeConsumeBuyProductService.getByEmployeeCost(employee, start, end);
					EmployeePerformance detail = new EmployeePerformance();
					detail.setEmployee(employee);
					detail.setFace_care_cost(map.get(Care.TYPE_FACE));
					detail.setBody_care_cost(map.get(Care.TYPE_BODY));
					detail.setDevice_care_cost(map.get(Care.TYPE_DEVICE));
					detail.setNew_card_cost(newCardCost);
					detail.setProduct_sale_cost(productCardCost);
					detail.setRecharge_card_cost(rechargeCardCost);
					float careCardCost = map.get(Care.TYPE_FACE) + map.get(Care.TYPE_BODY) + map.get(Care.TYPE_DEVICE);
					float total = newCardCost + rechargeCardCost + careCardCost + productCardCost;
					detail.setTotal(total);
					allMoney += total;
					if(total != 0) {
						list.add(detail);
					}
				}
			} catch (Exception e) {
			}
		}
        model.addAttribute("list", list);
        model.addAttribute("startDate", startDate);
        model.addAttribute("endDate", endDate);
        model.addAttribute("allMoney", allMoney);
		return "modules/employee/storeEmployeePerformanceList";
	}
	
	@RequestMapping(value = "form")
	public String form(StoreEmployeeAccounting storeEmployeeAccounting, Model model) {
		model.addAttribute("storeEmployeeAccounting", storeEmployeeAccounting);
		model.addAttribute("startDate", "");
        model.addAttribute("endDate", "");
		return "modules/employee/storeEmployeeAccountingForm";
	}

	@RequestMapping(value = "save")
	public String save(String jsonData, StoreEmployeeAccounting storeEmployeeAccounting, Model model, RedirectAttributes redirectAttributes) {
		JSONArray detailArray = (JSONArray) JSONSerializer.toJSON(Encodes
				.unescapeHtml(jsonData));
		storeEmployeeAccounting.setAccounting_time(new Date());
		storeEmployeeAccounting.setStore(StoreUtils.getStore());
		float allTotal = 0f;
		for (int i = 0; i < detailArray.size(); i++) {
			JSONObject detailObj = (JSONObject) detailArray.get(i);
			long employeeId = detailObj.getLong("employeeId");
			String title = detailObj.getString("title");
			float base_salary = Float.parseFloat(detailObj.getString("base_salary"));
			float new_card_bonus = Float.parseFloat(detailObj.getString("new_card_bonus"));
			float product_sale_bonus = Float.parseFloat(detailObj.getString("product_sale_bonus"));
			float do_care_bonus = Float.parseFloat(detailObj.getString("do_care_bonus"));
			float recharge_card_bonus = Float.parseFloat(detailObj.getString("recharge_card_bonus"));
			float float_salary = Float.parseFloat(detailObj.getString("float_salary"));
			float total = Float.parseFloat(detailObj.getString("total"));
			String remark = detailObj.getString("remark");
			StoreEmployeeAccountingDetail detail = new StoreEmployeeAccountingDetail();
			detail.setStoreEmployeeAccounting(storeEmployeeAccounting);
			detail.setEmployee(employeeService.get(employeeId));
			detail.setTitle(title);
			detail.setBase_salary(base_salary);
			detail.setNew_card_bonus(new_card_bonus);
			detail.setProduct_sale_bonus(product_sale_bonus);
			detail.setDo_care_bonus(do_care_bonus);
			detail.setRecharge_card_bonus(recharge_card_bonus);
			detail.setFloat_salary(float_salary);
			detail.setTotal(total);
			detail.setRemark(remark);
			storeEmployeeAccounting.getDetailList().add(detail);
			allTotal += total;
		}
		storeEmployeeAccounting.setTotal_salary(allTotal);
		if (!beanValidator(model, storeEmployeeAccounting)){
			return form(storeEmployeeAccounting, model);
		}
		storeEmployeeAccountingService.save(storeEmployeeAccounting);
		addMessage(redirectAttributes, "保存员工结算单成功");
		return "redirect:"+Global.ADMIN_PATH+"/employee/storeEmployeeAccounting/";
	}
	
	@RequestMapping(value = "delete")
	public String delete(Long id, RedirectAttributes redirectAttributes) {
		storeEmployeeAccountingService.delete(id);
		addMessage(redirectAttributes, "删除员工结算单成功");
		return "redirect:"+Global.ADMIN_PATH+"/employee/storeEmployeeAccounting/";
	}

	@RequestMapping(value = "satisfaction")
	public String satisfaction(HttpServletRequest request, HttpServletResponse response, Model model) {
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		List<Map<String, Map<Integer, Integer>>> allList = Lists.newArrayList();
		List<Map<String, Integer>> list = Lists.newArrayList();
		List<String> nameList = Lists.newArrayList();
		if(!StringUtils.isEmpty(startDate) || !StringUtils.isEmpty(endDate)){
			try {
				Date start = null;
				Date end = null;
				if (!StringUtils.isEmpty(startDate)) {
					start = DateUtils.getBeginOfDay(DateUtils.parseDate(startDate));
				}
				if (!StringUtils.isEmpty(endDate)) {
					end = DateUtils.getEndOfDay(DateUtils.parseDate(endDate));
				}
				List<Employee> employeeList = employeeService.findByStore(StoreUtils.getStore(), Employee.STATUS_WORKING);
				for (Employee employee : employeeList) {
					nameList.add(employee.getName());
					Map<String, Map<Integer, Integer>> currentMap = Maps.newConcurrentMap();
					Map<String, Integer> map = Maps.newConcurrentMap();
					Map<Integer, Integer> newCard = storeConsumeNewCardService.getByEmployeeSatisfaction(employee, start, end);
					Map<Integer, Integer> rechargeCard = storeConsumeRechargeCardService.getByEmployeeSatisfaction(employee, start, end);
					Map<Integer, Integer> careCard = storeConsumeDoCareService.getByEmployeeSatisfaction(employee, start, end);
					Map<Integer, Integer> productCard = storeConsumeBuyProductService.getByEmployeeSatisfaction(employee, start, end);
					int all = newCard.get(StoreConsume.TYPE_SATISFACTIOIN_1) + 
							rechargeCard.get(StoreConsume.TYPE_SATISFACTIOIN_1) + 
							careCard.get(StoreConsume.TYPE_SATISFACTIOIN_1) +
							productCard.get(StoreConsume.TYPE_SATISFACTIOIN_1);
					map.put(StoreConsume.TYPE_SATISFACTIOIN_1 + "", all);
					all = newCard.get(StoreConsume.TYPE_SATISFACTIOIN_2) + 
							rechargeCard.get(StoreConsume.TYPE_SATISFACTIOIN_2) + 
							careCard.get(StoreConsume.TYPE_SATISFACTIOIN_2) +
							productCard.get(StoreConsume.TYPE_SATISFACTIOIN_2);
					map.put(StoreConsume.TYPE_SATISFACTIOIN_2 + "", all);
					all = newCard.get(StoreConsume.TYPE_SATISFACTIOIN_3) + 
							rechargeCard.get(StoreConsume.TYPE_SATISFACTIOIN_3) + 
							careCard.get(StoreConsume.TYPE_SATISFACTIOIN_3) +
							productCard.get(StoreConsume.TYPE_SATISFACTIOIN_3);
					map.put(StoreConsume.TYPE_SATISFACTIOIN_3 + "", all);
					all = newCard.get(StoreConsume.TYPE_SATISFACTIOIN_4) + 
							rechargeCard.get(StoreConsume.TYPE_SATISFACTIOIN_4) + 
							careCard.get(StoreConsume.TYPE_SATISFACTIOIN_4) +
							productCard.get(StoreConsume.TYPE_SATISFACTIOIN_4);
					map.put(StoreConsume.TYPE_SATISFACTIOIN_4 + "", all);
					all = newCard.get(StoreConsume.TYPE_SATISFACTIOIN_5) + 
							rechargeCard.get(StoreConsume.TYPE_SATISFACTIOIN_5) + 
							careCard.get(StoreConsume.TYPE_SATISFACTIOIN_5) +
							productCard.get(StoreConsume.TYPE_SATISFACTIOIN_5);
					map.put(StoreConsume.TYPE_SATISFACTIOIN_5 + "", all);
					currentMap.put("newCard", newCard);
					currentMap.put("rechargeCard", rechargeCard);
					currentMap.put("careCard", careCard);
					currentMap.put("productCard", productCard);
					list.add(map);
					allList.add(currentMap);
				}
			} catch (Exception e) {
			}
		}
        model.addAttribute("list", list);
        model.addAttribute("nameList", nameList);
        model.addAttribute("jsonData", JsonMapper.getInstance().toJson(allList));
        model.addAttribute("nameJsonData", JsonMapper.getInstance().toJson(nameList));
        model.addAttribute("startDate", startDate);
        model.addAttribute("endDate", endDate);
		return "modules/employee/storeEmployeeSatisfactionList";
	}
}
